package com.cindata

import com.cindata.dictionary.*
import com.cindata.dimension.CreditScoreRiskDimension
import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import java.text.DecimalFormat
import java.text.SimpleDateFormat

@Secured(['isAuthenticated()'])
// @Transactional
class RiskWarningController
{
    def apiService
    def springSecurityService
    def scoreApiService
    def dataSource
    def componentService
    def riskWarningService
    def developerApiService
    def contactService
    def communityService

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    @Transactional
    def update(RiskWarning riskWarning)
    {
        if (riskWarning == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (riskWarning.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond riskWarning.errors, view: 'edit'
            return
        }

        riskWarning.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'riskWarning.label', default: 'RiskWarning'), riskWarning.id])
                redirect url: params['targetUri']
            }
            '*' { respond riskWarning, [status: OK] }
        }
    }

    def updateRiskWarning()
    {

    }

    /**
     * 押品价值波动列表
     */
    def priceFluctuationsRatioWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def city = params['city']
        def district = params['district']
        def residentialType = params['residentialType']
        def communityId = params['communityId']
        def user = User.findById(springSecurityService.principal.id)
        def sql = "from RiskWarning r where r.type.code = '1' and r.isWarning = '1' and r.bankAccount.id in " + Account.FilterAccountSql(user)
        if (city && city != '-1')
        {
            sql += " and r.collateral.city.zoneNumber = '${city}' "
        }
        if (district && district != '-1')
        {
            sql += " and r.collateral.district.zoneNumber = '${district}' "
        }
        if(residentialType){
            sql += " and r.collateral.estate.buildingType.id = ${residentialType} "
        }
        if(communityId){
            sql += " and r.collateral.estate.communityId = ${communityId} "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningcount = RiskWarning.executeQuery(sql1)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningcount: riskWarningcount[0], districtList: districtList, params: params]

    }
    /**
     * 押品价值波动详情
     */
    def priceFluctuationsRatioWarningShow(Collateral collateral)
    {
        def estate = null
        if(!collateral){
            estate = Estate.findById(Long.parseLong(params["id"]))
            collateral = Collateral.findByEstate(estate)
            params.status = RiskWarning.findByCollateral(collateral)?.status?.name
        }else{
            estate = collateral?.estate
        }
        println "params:   "+params

        def zoneNumber = estate?.city?.zoneNumber
        def communityId = estate.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage

        def replaceCollateral = collateral?.replacementCollateral

        respond collateral, model: [params: params, mortgageList: mortgageList, estateDetail: estate, community: community['data'], replaceCollateral: replaceCollateral, communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']]

    }
    /**
     * 押品价值波动处置
     */
    def disposalPriceFluctuations(Estate estate)
    {
        def status = ""
        try
        {
            estate.dealType = DataDict.findByCode("PriceFluctuations")
            estate.warningStatus = RiskWarningStatusDict.findByCode('3')
            estate.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 押品价值波动删除
     */
    def deletePriceFluctuations(Estate estate)
    {
        def status = ""
        try
        {
            estate.warningStatus = null
            estate.priceFluctuationsRatio = null
            estate.dealType = null
            estate.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 发布预警列表
     */
    def releasePriceFluctuationsWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def city = params['city']
        def district = params['district']
        def residentialType = params['residentialType']

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Collateral c where c.type.code = 'estate' and c.status = 'Completed' and c.account.id in " + Account.FilterAccountSql(user) + " and c.id not in ( select r.collateral.id from RiskWarning r where r.type.code = '1' and r.isWarning = '1') "
        if (city && city !='-1')
        {
            estateSql += " and c.city.zoneNumber = '${city}' "
        }
        if (district && district !='-1')

        {
            estateSql += " and c.district.zoneNumber = '${district}' "
        }
        if(residentialType){
            estateSql += " and c.estate.buildingType.id = ${residentialType} "
        }
        def sql1 = " select count(*) "+estateSql
        estateSql += " order by c.modifiedDate desc "
        def collateralList = Collateral.executeQuery(estateSql, [max: params.max, offset: params.offset]).asList()
        def collateralCount = Collateral.executeQuery(sql1)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond collateralList, model: [collateralList: collateralList, collateralCount: collateralCount[0], districtList: districtList, params: params], view: 'releasePriceFluctuationsWarning'

    }

    /**
     * 单条发布预警*/
    def toReleaseWarning(Estate estate)
    {
        def status = ""
        //价值波动率
        def priceFluctuationsRatio = params["priceFluctuationsRatio"]
        try
        {
            estate.priceFluctuationsRatio = priceFluctuationsRatio
            estate.warningStatus = RiskWarningStatusDict.findByCode('2')
            estate.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)
    }

    /**
     * 多条发布预警
     */
    def multitermReleaseWarning()
    {
        def status = ""
        //价值波动率
        def ids = params["ids"]
        try
        {
            def idList = new ArrayList()
            if (ids)
            {
                idList = ids.split(",")
            }
            idList?.each {
                def collateral = Collateral.findById(Long.parseLong(it))
                //预警
                def type = RiskWarningTypeDict.findByCode("1")
                def state = RiskWarningStatusDict.findByCode("2")
                def riskWarning = RiskWarning.findByCollateralAndType(collateral, type)
                if (!riskWarning)
                {
                    riskWarning = new RiskWarning()
                }
                riskWarning.type = type
                riskWarning.collateral = collateral
                riskWarning.status = state
                if (riskWarning.validate())
                {
                    riskWarning.save()
                }
                else
                {
                    println riskWarning.errors
                }
            }
            status = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)
    }

    def searchConditionSql(params, estateQueryParam)
    {
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //房屋用途
        def residentialType = params["residentialType"]
        //价值波动率
        def priceFluctuationsRatio = params["priceFluctuationsRatio"]
        //小区id
        def communityId = params["communityId"]
        if (communityId)
        {
            def cityNumber = Estate.findByCommunityId(communityId)?.city?.zoneNumber
            if (cityNumber)
            {
                params['city'] = cityNumber
            }
            def districtNumber = Estate.findByCommunityId(communityId)?.district?.zoneNumber
            if (districtNumber)
            {
                params['district'] = districtNumber
            }
        }

        def estateSql = " "
        if (city && city != "-1")
        {
            estateSql += " and e.city.zoneNumber = :city "
            estateQueryParam["city"] = city
        }
        if (district && district != "-1")
        {
            estateSql += " and e.district.zoneNumber = :district "
            estateQueryParam["district"] = district
        }
        if (residentialType && residentialType != '')
        {
            estateSql += " and e.estate.buildingType.code = :residentialType "
            estateQueryParam['residentialType'] = residentialType
        }
        if (priceFluctuationsRatio && priceFluctuationsRatio != '')
        {
            estateSql += " and e.estate.priceFluctuationsRatio = :priceFluctuationsRatio "
            estateQueryParam['priceFluctuationsRatio'] = priceFluctuationsRatio
        }

        return estateSql
    }

    def districtList()
    {
        if (params["city"] == '-1')
        {
            return ''
        }
        else
        {
            render([districtList: District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(params["city"], 2), 3)] as JSON)
        }
    }
    
    /**
     * 命中反欺诈
     */
    def antiFraudWarning(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)

        def order = params["order"]
        def sort = params["sort"]
        def city = params["city"]
        def district = params["district"]
        def borrName = params['borrName']
        def borrIdCardNo = params["borrIdCardNo"]
        def serialNumber = params["serialNumber"]

        def mortgageList = new ArrayList()
        def mortgageQueryParam = new HashMap()
        String mortgageSql = " from Mortgage e where e.warningStatus.code in ('2', '3') and e.account.id in " + Account.FilterAccountSql(user)
        if (city && city != 'null' && city != '-1')
        {
            mortgageSql += " and e.account.city.zoneNumber = :city "
            mortgageQueryParam['city'] = city
        }
        if (district && district != 'null' && district != '-1')
        {
            mortgageSql += " and e.account.district.zoneNumber = :district "
            mortgageQueryParam['district'] = district
        }
        if (serialNumber && serialNumber != '')
        {
            mortgageSql += " and e.serialNumber = :serialNumber "
            mortgageQueryParam['serialNumber'] = serialNumber
        }
        if (borrName && borrName != '')
        {
            mortgageSql += " and e.borrName like :borrName "
            mortgageQueryParam['borrName'] = '%' + borrName + '%'
        }
        if (borrIdCardNo && borrIdCardNo != "")
        {
            mortgageSql += " and e.borrIdCardNo like :borrIdCardNo "
            mortgageQueryParam['borrIdCardNo'] = '%' + borrIdCardNo + '%'
        }

        //查询总数
        String countSql = "select count(e.id) " + mortgageSql
        mortgageSql += " order by e.modifiedDate desc "
        mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def mortgageCount = Mortgage.executeQuery(countSql, mortgageQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond mortgageList, model: [mortgageCount: mortgageCount[0], params: params, districtList: districtList], view: 'antiFraudWarning'
    }

    /**
     * 命中反欺诈处置
     */
    def disposalAntiFraud(Mortgage mortgage)
    {
        def status = ""
        //预警状态
        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('3')
        def dealType = RiskWarningDealTypeDict.findByCode("IsAntiFraud")
        try
        {
            mortgage.warningStatus = riskWarningStatusDict
            mortgage.dealType = dealType
            mortgage.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 命中反欺诈删除
     */
    def deleteAntiFraud(Mortgage mortgage)
    {
        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('1')
        def status = ""
        try
        {
            mortgage.warningStatus = riskWarningStatusDict
            mortgage.dealType = null
            mortgage.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 命中反欺诈发布
     */
    def releaseAntiFraudWarning(Integer max)
    {
        def user = User.findById(springSecurityService.principal.id)

        def city = params["city"]
        def district = params["district"]
        def serialNumber = params["serialNumber"]
        def borrName = params['borrName']
        def borrIdCardNo = params["borrIdCardNo"]
        def mortgageList = new ArrayList()
        def mortgageQueryParam = new HashMap()
        String mortgageSql = " from Mortgage e where e.warningStatus.code = '1' and e.account.id in " + Account.FilterAccountSql(user)
        if (city && city != 'null' && city != '-1')
        {
            mortgageSql += " and e.account.city.zoneNumber = :city "
            mortgageQueryParam['city'] = city
        }
        if (district && district != 'null' && district != '-1')
        {
            mortgageSql += " and e.account.district.zoneNumber = :district "
            mortgageQueryParam['district'] = district
        }
        if (serialNumber && serialNumber != '')
        {
            mortgageSql += " and e.serialNumber = :serialNumber "
            mortgageQueryParam['serialNumber'] = serialNumber
        }
        if (borrName && borrName != '')
        {
            mortgageSql += " and e.borrName like :borrName "
            mortgageQueryParam['borrName'] = '%' + borrName + '%'
        }
        if (borrIdCardNo && borrIdCardNo != "")
        {
            mortgageSql += " and e.borrIdCardNo like :borrIdCardNo "
            mortgageQueryParam['borrIdCardNo'] = '%' + borrIdCardNo + '%'
        }

        //查询总数
        String countSql = "select count(e.id) " + mortgageSql
        mortgageSql += " order by e.modifiedDate desc "
        mortgageList = Mortgage.executeQuery(mortgageSql, mortgageQueryParam, [max: params.max ?: 10, offset: params.offset ?: 0])
        def mortgageCount = Mortgage.executeQuery(countSql, mortgageQueryParam)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond mortgageList, model: [mortgageCount: mortgageCount[0], params: params, districtList: districtList], view: 'releaseAntiFraudWarning'
    }

    /**
     * 单条发布预警1*/
    def toReleaseWarning1(Mortgage mortgage)
    {
        def status = ""
        //预警状态
        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('2')
        try
        {
            mortgage.warningStatus = riskWarningStatusDict
            mortgage.save flush: true
            status = "success"

        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)

    }

    /**
     * 多条发布预警1*/
    def multitermReleaseWarning1()
    {
        def status = ""
        //预警状态
        def riskWarningStatusDict = RiskWarningStatusDict.findByCode('2')
        def ids = params["ids"]
        try
        {
            def idList = new ArrayList()
            if (ids)
            {
                idList = ids.split(",")
            }
            idList?.each {
                def mortgage = Mortgage.findById(Long.parseLong(it))
                mortgage.warningStatus = riskWarningStatusDict
                mortgage.save flush: true
            }
            status = "success"
        }
        catch (Exception e)
        {
            e.printStackTrace()
            status = "false"
        }
        render([status: status] as JSON)

    }

    /**
     * 集中度风险统计*/
    def concentrationRisk()
    {

    }

    //楼盘评分预警
    def buildingScoreWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '15' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    /**
     * 前往流通性评估页面
     */
    def buildingScoreWarningShow()
    {
        def zoneNumber = params['city']
        def communityId = Long.parseLong(params['id'])
        params.status = RiskWarning.findByCommunity(Community.findByCommunityId(communityId))?.status?.name
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //流动性评分
        def score = scoreApiService.communityLiquidityScore(communityId.toString())
        //小区价格走势
        def rate = apiService.communityRate(zoneNumber, communityId.toString())
        //获取上月数据
        def listingCount = 0
        def saleCount = 0
        def averPrice = 0
        def month = apiService.communityLastMonthRate(zoneNumber, communityId.toString())
        if (month?.data?.echartDate?.size() > 0)
        {
            //获取挂牌案例数量
            listingCount = month?.data?.echartDate[0]?.numberCount ? month?.data?.echartDate[0]?.numberCount : 0
            //获取成交案例数量
            //暂时不用def saleCount = month?.data?.echartDate[0]?.saleCount ? month?.data?.echartDate[0]?.saleCount : 0
            //获取小区均价
            averPrice = month?.data?.echartDate[0]?.price ? month?.data?.echartDate[0]?.price : 0
        }
        println "score--" + score
        println "month--" + month
        println "rate--" + rate
        
        //小区1年内的小区价格走势
        def trendPriceCommunityData = []
        def trendPriceCommunityDate = []

        //小区1年内的挂牌量趋势
        def trendNetlistData = []
        def trendNetlistDate = []

        //小区1年内小区的交易量趋势
        def communityTrendSaleData = []
        def communityTrendSaleDate = []

        if(rate?.data?.echartDate){
            rate?.data?.echartDate.each{
                trendPriceCommunityData.push(it?.price)
                trendPriceCommunityDate.push(it?.monthDate)
                trendNetlistData.push(it?.numberCount)
                trendNetlistDate.push(it?.monthDate)
                communityTrendSaleData.push(it?.saleCount)
                communityTrendSaleDate.push(it?.monthDate)
                println it?.saleCount
                saleCount = saleCount + it?.saleCount
            }

        }

        //查询权值
        def communityScoreWeight = CommunityScoreWeight.list().get(0)



        def closingWeight = communityScoreWeight.closingWeight
        // 成交率权重
        def listingWeight = communityScoreWeight.listingWeight
        // 挂牌率权重
        def dealAvgDayWeight = communityScoreWeight.dealAvgDayWeight
        // 成交周期权重
        def discountrateWeight = communityScoreWeight.discountrateWeight
        // 折价比权重
        def foreclosureTimesWeight = communityScoreWeight.foreclosureTimesWeight
        // 法拍次数权重

        //小区配套权值
        def ifSchoolZoneScoreWeight = communityScoreWeight.schoolDistrictsWeight
        def communityTrafficScoreWeight = communityScoreWeight.trafficWeight
        def houseAgeScoreWeight = communityScoreWeight.houseAgeWeight
        def communityHospitalScoreWeight = communityScoreWeight.hospitalWeight
        def communityMallScoreWeight = communityScoreWeight.mallWeight
        def communityGreeningrateScoreWeight = communityScoreWeight.afforestationWeight
        def communityPlotratioScoreWeight = communityScoreWeight.ratioWeight
        def communityParkScoreWeight = communityScoreWeight.parkWeight
        def communityPmfeeScoreWeight = communityScoreWeight.propertyFeeWeight
        def communitySupermarketScoreWeight = communityScoreWeight.superMarketWeight
        def communityBankScoreWeight = communityScoreWeight.bankWeight

        def scenicWeight = communityScoreWeight.scenicWeight
        def noisePullutionWeight = communityScoreWeight.noisePullutionWeight
        def airPullutionWeight = communityScoreWeight.airPullutionWeight

        //小区总分
        def liquidWeight = communityScoreWeight.liquidityWeight
        def surroundWeight = communityScoreWeight.assortWeight
        def natureWeight = communityScoreWeight.natureWeight

        //小区配套评分
        def ifSchoolZoneScore = 0
        def communityTrafficScore = 0
        def houseAgeScore = 0
        def communityHospitalScore = 0
        def communityMallScore = 0
        def communityGreeningrateScore = 0
        def communityPlotratioScore = 0
        def communityParkScore = 0
        def communityPmfeeScore = 0
        def communitySupermarketScore = 0
        def communityBankScore = 0

        //流动性评分
        def closingScore = 0
        def dealAvgDayScore = 0
        def listingScore = 0
        def discountrateScore = 0
        def foreclosureTimesScore = 0

        def scenicScore = 0
        def noisePullutionScore = 0
        def airPullutionScore = 0

        //小区配套总分
        def communitySurroundingScore = 0

        //小区流动性总分
        def liquidityScore = 0

        //小区自然总分
        def natureScore = 0

        def scoreArr = []
        def surroudArr = []
        def natureArr = []

        DecimalFormat df = new DecimalFormat("#.00");
        DecimalFormat df1 = new DecimalFormat("#.0");
        if (score?.closingScore)
        {
            //成交率评分
            closingScore = (score?.closingScore ? score?.closingScore : 0) * closingWeight
            //成交周期评分
            dealAvgDayScore = (score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) * dealAvgDayWeight
            //挂牌率评分
            listingScore = (score?.listingScore ? score?.listingScore : 0) * listingWeight
            //折价比例评分（法拍计算）
            discountrateScore = (score?.discountrateScore ? score?.discountrateScore : 0) * discountrateWeight
            //法拍次数评分
            foreclosureTimesScore = (score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) * foreclosureTimesWeight

            ifSchoolZoneScore = (score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) * ifSchoolZoneScoreWeight
            communityTrafficScore = (score?.communityTrafficScore ? score?.communityTrafficScore : 0) * communityTrafficScoreWeight
            houseAgeScore = (score?.houseAgeScore ? score?.houseAgeScore : 0) * houseAgeScoreWeight
            communityHospitalScore = (score?.communityHospitalScore ? score?.communityHospitalScore : 0) * communityHospitalScoreWeight
            communityMallScore = (score?.communityMallScore ? score?.communityMallScore : 0) * communityMallScoreWeight
            communityGreeningrateScore = (score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) * communityGreeningrateScoreWeight
            communityPlotratioScore = (score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) * communityPlotratioScoreWeight
            communityParkScore = (score?.communityParkScore ? score?.communityParkScore : 0) * communityParkScoreWeight
            communityPmfeeScore = (score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) * communityPmfeeScoreWeight
            communitySupermarketScore = (score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) * communitySupermarketScoreWeight
            communityBankScore = (score?.communityBankScore ? score?.communityBankScore : 0) * communityBankScoreWeight

            scenicScore = (score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) * scenicWeight
            noisePullutionScore = (score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) * noisePullutionWeight
            airPullutionScore = (score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) * airPullutionWeight

            communitySurroundingScore = ifSchoolZoneScore + communityTrafficScore + houseAgeScore + communityHospitalScore + communityMallScore + communityGreeningrateScore + communityPlotratioScore + communityParkScore + communityPmfeeScore + communitySupermarketScore + communityBankScore

            liquidityScore = closingScore + dealAvgDayScore + listingScore + discountrateScore + foreclosureTimesScore

            natureScore = scenicScore + noisePullutionScore + airPullutionScore

            scoreArr = "[" + df.format(score?.closingScore ? score?.closingScore : 0) + "," + df.format(score?.dealAverageDayScore ? score?.dealAverageDayScore : 0) + "," + df.format(score?.listingScore ? score?.listingScore : 0) + "," + df.format(score?.discountrateScore ? score?.discountrateScore : 0) + "," + df.format(score?.foreclosureTimesScore ? score?.foreclosureTimesScore : 0) + "]"
            surroudArr = "[" + df.format(score?.ifSchoolZoneScore ? score?.ifSchoolZoneScore : 0) + "," + df.format(score?.communityTrafficScore ? score?.communityTrafficScore : 0) + "," + df.format(score?.houseAgeScore ? score?.houseAgeScore : 0) + "," + df.format(score?.communityHospitalScore ? score?.communityHospitalScore : 0) + "," + df.format(score?.communityMallScore ? score?.communityMallScore : 0) + "," + df.format(score?.communityGreeningrateScore ? score?.communityGreeningrateScore : 0) + "," + df.format(score?.communityPlotratioScore ? score?.communityPlotratioScore : 0) + "," + df.format(score?.communityParkScore ? score?.communityParkScore : 0) + "," + df.format(score?.communityPmfeeScore ? score?.communityPmfeeScore : 0) + "," + df.format(score?.communitySupermarketScore ? score?.communitySupermarketScore : 0) + "," + df.format(score?.communityBankScore ? score?.communityBankScore : 0) + "]"
            natureArr = "[" + df.format(score?.communityRecentlyScenicScore ? score?.communityRecentlyScenicScore : 0) + "," + df.format(score?.communityRecentlySubwayScore ? score?.communityRecentlySubwayScore : 0) + "," + df.format(score?.communityRecentlyPollutionScore ? score?.communityRecentlyPollutionScore : 0) + "]"
            println surroudArr
        }


        def communityScore = liquidityScore * liquidWeight + communitySurroundingScore * surroundWeight + natureScore * natureWeight

        //查询所有押品数量
        def estateCount = Estate.executeQuery("select count(e.id) from Estate e where e.communityId = ${communityId} and e.account.id in " +Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))

        //计算押品均价
        def estateList = Estate.executeQuery(" select unitPrice,loansBalance,loansEvaluateTotalPrice from Estate e where e.communityId = ${communityId} and e.account.id in " +Account.FilterAccountSql(User.findById(springSecurityService.principal.id)))
        //def list = sql.rows
        def totalUnitPrice = 0
        def sumLoansBalance = 0
        def sumLoansEvaluatePrice = 0
        def avgUnitPrice = 0
        def avgCltv = 0
        estateList.each {
            totalUnitPrice += it[0] ? it[0] : 0
            sumLoansBalance += it[1] ? it[1]: 0
            sumLoansEvaluatePrice += it[2] ? it[2] : 0
        }
        println community
        if (estateList && sumLoansEvaluatePrice != 0)
        {
            //押品均价
            avgUnitPrice = totalUnitPrice / estateList.size()
            //动态抵押率
            avgCltv = sumLoansBalance / sumLoansEvaluatePrice
        }
        //成交周期
        def saleCycle = score?.dealAverageDay
        respond liquidityScore,
                model: [liquidityScore: df1.format(liquidityScore),
                        communitySurroundingScore: df1.format(communitySurroundingScore),
                        natureScore:df1.format(natureScore),
                        communityScore: df1.format(communityScore),
                        communityId: communityId,
                        scoreArr: scoreArr,
                        surroudArr: surroudArr,
                        natureArr:natureArr,
                        community: community?.data,
                        estateCount: estateCount[0],
                        avgUnitPrice: avgUnitPrice,
                        avgCltv: avgCltv,
                        listingCount: listingCount,
                        saleCount: saleCount,
                        saleCycle: saleCycle,
                        averPrice: averPrice,
                        trendPriceCommunityData: trendPriceCommunityData,
                        trendPriceCommunityDate: trendPriceCommunityDate,
                        trendNetlistData: trendNetlistData,
                        trendNetlistDate: trendNetlistDate,
                        communityTrendSaleData: communityTrendSaleData,
                        communityTrendSaleDate: communityTrendSaleDate,
                        score: score], view: "buildingScoreWarningShow"
    }

    /**
     * 人员关系预警*/
    def contactRelationsWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 8, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def user = User.findById(springSecurityService.principal.id)

        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "

        // def highList = CreditScoreRiskDimension.findByLabel("高风险")
        def highList = CreditScoreRiskDimension.findByOrderNumber("1")
        def maxValue = highList?.maxValue
        sql += " and e.creditScore <= :maxValue "
        estateQueryParam['maxValue'] = new Double(maxValue)

        if (address && address != "")
        {
            sql += " and e.address like :address"
            estateQueryParam['address'] = '%' + address + '%'
        }
        if (debitCardNumber && debitCardNumber != "")
        {
            sql += " and e.debitCardNumber like :debitCardNumber"
            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        }
        if (creditRiskLevel && creditRiskLevel != "")
        {
            def riskList = CreditScoreRiskDimension.list()
            riskList.each {
                if (it?.label == creditRiskLevel)
                {
                    def minScoreValue = it.minValue
                    def maxScoreValue = it.maxValue
                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
                }
            }
        }
        if (cellphone && cellphone != "")
        {
            sql += " and e.cellphone like :cellphone"
            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        }
        if (creditScoreStart && creditScoreStart != '')
        {
            sql += " and e.creditScore >= :creditScoreStart "
            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        }
        if (creditScoreEnd && creditScoreEnd != '')
        {
            sql += " and e.creditScore <= :creditScoreEnd "
            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        }
        if (fullName && fullName != "")
        {
            sql += " and e.fullName like :fullName"
            estateQueryParam['fullName'] = '%' + fullName + '%'
        }
        if (idNumber && idNumber != "")
        {
            sql += " and e.idNumber = :idNumber "
            estateQueryParam['idNumber'] = idNumber
        }
        if (identityType && identityType != "")
        {
            sql += " and e.identityType.id = :identityType "
            estateQueryParam['identityType'] = Long.parseLong(identityType)
        }

        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        contactSql += sql

        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond contactList, model: [contactList: contactList, contactCount: contactCount[0], params: params]

    }
    /**个人拓扑关系图
     * */
    def contactRelationsWarningShow()
    {

    }

    /**个人信用等级预警
     * */
    def contactCreditLevelWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 4, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def user = User.findById(springSecurityService.principal.id)

        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "

        if (address && address != "")
        {
            sql += " and e.address like :address"
            estateQueryParam['address'] = '%' + address + '%'
        }
        if (debitCardNumber && debitCardNumber != "")
        {
            sql += " and e.debitCardNumber like :debitCardNumber"
            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        }
        if (creditRiskLevel && creditRiskLevel != "")
        {
            def riskList = CreditScoreRiskDimension.list()
            riskList.each {
                if (it?.label == creditRiskLevel)
                {
                    def minScoreValue = it.minValue
                    def maxScoreValue = it.maxValue
                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
                }
            }
        }
        if (cellphone && cellphone != "")
        {
            sql += " and e.cellphone like :cellphone"
            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        }
        if (creditScoreStart && creditScoreStart != '')
        {
            sql += " and e.creditScore >= :creditScoreStart "
            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        }
        if (creditScoreEnd && creditScoreEnd != '')
        {
            sql += " and e.creditScore <= :creditScoreEnd "
            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        }
        if (fullName && fullName != "")
        {
            sql += " and e.fullName like :fullName"
            estateQueryParam['fullName'] = '%' + fullName + '%'
        }
        if (idNumber && idNumber != "")
        {
            sql += " and e.idNumber = :idNumber "
            estateQueryParam['idNumber'] = idNumber
        }
        if (identityType && identityType != "")
        {
            sql += " and e.identityType.id = :identityType "
            estateQueryParam['identityType'] = Long.parseLong(identityType)
        }

        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql

//        if (order && sort)
//        {
//           sql += " order by e.${sort} ${order}"
//        }
//        else
//        {
            sql += " order by e.fullName desc "
//        }
        contactSql += sql

        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond contactList, model: [contactList: contactList, contactCount: contactCount[0], params: params], view: 'contactCreditLevelWarning'
    }

    //个人信用等级预警详情
    def contactCreditLevelWarningShow(Contact contact){

        respond contact
    }

    //舆情预警
    def publicOpinionWarning()
    {
    }
    //舆情预警
    def publicOpinionShow()
    {
        def type = params['id']
        respond true, view:'publicOpinionShow'+type
    }

    //逾期/违约（企业）
    def accountOverdueWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 4, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (registeredCapitalStart && registeredCapitalStart != "")
        {
            sql += "and e.registeredCapital >= :registeredCapitalStart "
            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        }
        if (registeredCapitalEnd && registeredCapitalEnd != "")
        {
            sql += "and e.registeredCapital <= :registeredCapitalEnd "
            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        }
        if (creditLevel && creditLevel != "")
        {
            sql += " and e.creditLevel like :creditLevel "
            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        }
        if (operatingState && operatingState != "")
        {
            sql += " and e.operatingState = :operatingState "
            estateQueryParam['operatingState'] = operatingState
        }
        if (unitNature && unitNature != "")
        {
            sql += " and e.unitNature.id = :unitNature "
            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        }

        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql

        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond accountList, model: [accountCount: accountCount[0], params: params]
    }

    //逾期/违约（对公）详情
    def accountOverdueWarningShow(){

    }

    //逾期/违约（个人）
    def contactOverdueWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def user = User.findById(springSecurityService.principal.id)

        def fullName = params['fullName']
        def identityType = params['identityType']
        def idNumber = params['idNumber']
        def cellphone = params['cellphone']
        def defaultStart = params['defaultStart']
        def defaultEnd = params['defaultEnd']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']
        def disposalMethod = params['disposalMethod']
        def serialNumber = params['serialNumber']
        def stage = params['stage']
        
        def sql = "from RiskWarning r where r.type.code = '8' and r.isWarning = '1'"
        if (fullName)
        {
            sql += " and r.mortgage.mortgageContact.fullName like '%${fullName}%'"
        }
        if (identityType)
        {
            sql += " and r.mortgage.mortgageContact.identityType.id = ${identityType}"
        }
        if (idNumber) 
        {
            sql += " and r.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
        }
        if (cellphone) 
        {
            sql += " and r.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
        }
        if (defaultStart && defaultStart != "")
        {
            sql += " and r.mortgage.curDefaultingDuration >= ${defaultStart}"
        }
        if (defaultEnd && defaultEnd != "")
        {
            sql += " and r.mortgage.curDefaultingDuration <= ${defaultEnd}"
        }
        if (overdueStart && overdueStart != "")
        {
            sql += " and r.mortgage.curOverdueDuration >= ${overdueStart}"
        }
        if (overdueEnd && overdueEnd != "")
        {
            sql += " and r.mortgage.curOverdueDuration <= ${overdueEnd}"
        }
        if (disposalMethod) 
        {
            sql += " and r.disposalMethod.id = ${disposalMethod}"
        }
        if (stage) 
        {
            sql += " and r.stage.id = ${stage}"
        }
        if (serialNumber) 
        {
            sql += " and r.mortgage.serialNumber like '${serialNumber}'"
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    def contactOverdueWarningIndex()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        def user = User.findById(springSecurityService.principal.id)
        
        def fullName = params['fullName']
        def identityType = params['identityType']
        def idNumber = params['idNumber']
        def cellphone = params['cellphone']
        def defaultStart = params['defaultStart']
        def defaultEnd = params['defaultEnd']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']
        def disposalDepartment = params['disposalDepartment']
        def serialNumber = params['serialNumber']
        def stage = params['stage']

        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList) 
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def riskWarningSql = "select f.riskWarning from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")"
        def riskWarningList1 = RiskWarningFlowStage.executeQuery(riskWarningSql, [max: max, offset: offset])
        if (riskWarningList1[0]?.disposalDepartment && riskWarningList1[0]?.stage?.code == '13')
        {
            riskWarningSql += " and c.disposalDepartment.id = ${user?.department?.id}"
        }
        if (riskWarningList1[0]?.disposalUser && riskWarningList1[0]?.stage?.code == '16') 
        {
            riskWarningSql += " and c.disposalUser.id = ${user?.id}"
        }

        // 所有催收列表
        if (params['flag']) 
        {
            riskWarningSql = "from RiskWarning c where c.type.code = '8' and c.isWarning = '1' and c.disposalMethod.code = '3'"    
        }

        def sql = " "
        if (fullName)
        {
            sql += " and c.mortgage.mortgageContact.fullName like '%${fullName}%'"
        }
        if (identityType)
        {
            sql += " and c.mortgage.mortgageContact.identityType.id = ${identityType}"
        }
        if (idNumber) 
        {
            sql += " and c.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
        }
        if (cellphone) 
        {
            sql += " and c.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
        }
        if (defaultStart && defaultStart != "")
        {
            sql += " and c.mortgage.curDefaultingDuration >= ${defaultStart}"
        }
        if (defaultEnd && defaultEnd != "")
        {
            sql += " and c.mortgage.curDefaultingDuration <= ${defaultEnd}"
        }
        if (overdueStart && overdueStart != "")
        {
            sql += " and c.mortgage.curOverdueDuration >= ${overdueStart}"
        }
        if (overdueEnd && overdueEnd != "")
        {
            sql += " and c.mortgage.curOverdueDuration <= ${overdueEnd}"
        }
        if (disposalDepartment) 
        {
            sql += " and c.disposalDepartment.id = ${disposalDepartment}"
        }
        if (stage) 
        {
            sql += " and c.stage.id = ${stage}"
        }
        if (serialNumber) 
        {
            sql += " and c.mortgage.serialNumber like '${serialNumber}'"
        }
        def countSql = "select count(c.id) from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")" + sql
        if (params['flag']) 
        {
            countSql = "select count(c.id) " + riskWarningSql
        }
        sql += " order by c.modifiedDate desc "

        println "riskWarningSql:" + riskWarningSql + sql
        println "countSql:" + countSql
        def riskWarningList = RiskWarningFlowStage.executeQuery(riskWarningSql + sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarningFlowStage.executeQuery(countSql)
        
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    // 诉讼列表
    // def overdueLitigationIndex()
    // {
    //     def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    //     def offset = params.offset ? params.offset.toInteger() : 0
    //     def user = User.findById(springSecurityService.principal.id)
        
    //     def fullName = params['fullName']
    //     def identityType = params['identityType']
    //     def idNumber = params['idNumber']
    //     def cellphone = params['cellphone']
    //     def defaultStart = params['defaultStart']
    //     def defaultEnd = params['defaultEnd']
    //     def overdueStart = params['overdueStart']
    //     def overdueEnd = params['overdueEnd']
    //     def disposalDepartment = params['disposalDepartment']
    //     def stage = params['stage']

    //     def roleSql = ""
    //     def roleList = UserRole.findAllByUser(user)*.role
    //     if (roleList) 
    //     {
    //         String roleIdList = roleList*.id?.toString()
    //         roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
    //     }

    //     def riskWarningSql = "select f.riskWarning from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")"
    //     // 所有催收列表
    //     if (params['flag']) 
    //     {
    //         riskWarningSql = "from RiskWarning c where c.type.code = '8' and c.isWarning = '1' and c.disposalMethod.code in ('1', '2')"    
    //     }
    //     def sql = " "
    //     if (fullName)
    //     {
    //         sql += " and c.mortgage.mortgageContact.fullName like '%${fullName}%'"
    //     }
    //     if (identityType)
    //     {
    //         sql += " and c.mortgage.mortgageContact.identityType.id = ${identityType}"
    //     }
    //     if (idNumber) 
    //     {
    //         sql += " and c.mortgage.mortgageContact.idNumber like '%${idNumber}%'"
    //     }
    //     if (cellphone) 
    //     {
    //         sql += " and c.mortgage.mortgageContact.cellphone like '%${cellphone}%'"
    //     }
    //     if (defaultStart && defaultStart != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration >= ${defaultStart}"
    //     }
    //     if (defaultEnd && defaultEnd != "")
    //     {
    //         sql += " and c.mortgage.curDefaultingDuration <= ${defaultEnd}"
    //     }
    //     if (overdueStart && overdueStart != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration >= ${overdueStart}"
    //     }
    //     if (overdueEnd && overdueEnd != "")
    //     {
    //         sql += " and c.mortgage.curOverdueDuration <= ${overdueEnd}"
    //     }
    //     if (disposalDepartment) 
    //     {
    //         sql += " and c.disposalDepartment.id = ${disposalDepartment}"
    //     }
    //     if (stage) 
    //     {
    //         sql += " and c.stage.id = ${stage}"
    //     }

    //     def countSql = "select count(c.id) from RiskWarningFlowStage f left join f.riskWarning c where c.type.code = '8' and c.isWarning = '1' and f.stage.id = c.stage.id and f.id in (select flowStage.id from RiskWarningFlowStageRole where teamRole.code = 'Approval'" + roleSql + ")" + sql
    //     if (params['flag']) 
    //     {
    //         countSql = "select count(c.id) " + riskWarningSql
    //     }
    //     sql += " order by c.modifiedDate desc "

    //     def riskWarningList = RiskWarningFlowStage.executeQuery(riskWarningSql + sql, [max: max, offset: offset])
    //     def riskWarningCount = RiskWarningFlowStage.executeQuery(countSql)

    //     respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    // }

    //逾期/违约（个人）详情
    def contactOverdueWarningShow(RiskWarning riskWarning)
    {
        def mortgage = riskWarning?.mortgage
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList) 
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }
        def editRoleFlag = false
        def approveRoleFlag = false
        if (flowStage) 
        {
            editRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.EDIT()?.id]) && true
            approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        }

        def layout = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)?.layout?.name
        respond mortgage, model: [editRoleFlag: editRoleFlag, approveRoleFlag: approveRoleFlag, params: params, riskWarning: riskWarning, contact: mortgage.mortgageContact], view: layout
    }

    //信用等级预警（企业）
    def accountCreditLevelWarning(){
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0
        //城市
        def city = params["city"]
        //行政区
        def district = params["district"]
        //注册资金
        def registeredCapitalStart = params["registeredCapitalStart"]
        //注册资金
        def registeredCapitalEnd = params["registeredCapitalEnd"]
        //信用评级
        def creditLevel = params["creditLevel"]
        //企业名称
        def name = params["name"]
        //经营状态
        def operatingState = params["operatingState"]
        //单位性质
        def unitNature = params["unitNature"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]

        def user = User.findById(springSecurityService.principal.id)
        def estateSql = " from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (name && name != "")
        {
            sql += " and e.name like :name"
            estateQueryParam['name'] = '%' + name + '%'
        }
        if (city && city != "-1")
        {
            sql += " and e.city.zoneNumber = :city "
            estateQueryParam['city'] = city
        }
        if (district && district != "-1")
        {
            sql += " and e.district.zoneNumber = :district "
            estateQueryParam['district'] = district
        }
        if (registeredCapitalStart && registeredCapitalStart != "")
        {
            sql += "and e.registeredCapital >= :registeredCapitalStart "
            estateQueryParam['registeredCapitalStart'] = new BigDecimal(registeredCapitalStart) * 10000
        }
        if (registeredCapitalEnd && registeredCapitalEnd != "")
        {
            sql += "and e.registeredCapital <= :registeredCapitalEnd "
            estateQueryParam['registeredCapitalEnd'] = new BigDecimal(registeredCapitalEnd) * 10000
        }
        if (creditLevel && creditLevel != "")
        {
            sql += " and e.creditLevel like :creditLevel "
            estateQueryParam['creditLevel'] = "%" + creditLevel + "%"
        }
        if (operatingState && operatingState != "")
        {
            sql += " and e.operatingState = :operatingState "
            estateQueryParam['operatingState'] = operatingState
        }
        if (unitNature && unitNature != "")
        {
            sql += " and e.unitNature.id = :unitNature "
            estateQueryParam['unitNature'] = Long.parseLong(unitNature)
        }

        def countSql = " select count(e.id) from Account e where e.type.code = 'MortgageAccount' and e.bankAccount.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        estateSql += sql

        def accountList = Account.executeQuery(estateSql, estateQueryParam, [max: max, offset: offset])
        def accountCount = Account.executeQuery(countSql, estateQueryParam)
        respond accountList, model: [accountCount: accountCount[0], params: params]

    }

    def accountCreditLevelWarningShow(){

    }

    def contactRiskWarning()
    {
        def max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        def offset = params.offset ? params.offset.toInteger() : 0

        def fullName = params["fullName"]
        def identityType = params["identityType"]
        def idNumber = params["idNumber"]
        def estateQueryParam = new HashMap()
        def sort = params["sort"]
        def order = params["order"]
        def address = params["address"]
        def debitCardNumber = params["debitCardNumber"]
        def creditRiskLevel = params["creditRiskLevel"]
        def creditScoreStart = params["creditScoreStart"]
        def creditScoreEnd = params["creditScoreEnd"]
        def cellphone = params["cellphone"]
        def batch = params["batch"]
        def user = User.findById(springSecurityService.principal.id)

        def riskSql = "from ContactRiskWarningDisposition c where 1=1"
        def riskWarningStatus = params['riskWarningStatus']
        if (riskWarningStatus)
        {
            riskSql += " and c.status = '${riskWarningStatus}'"
        }
        def riskWarningDispositionType = params['riskWarningDispositionType']
        if (riskWarningDispositionType)
        {
            riskSql += " and c.type.id = ${riskWarningDispositionType}"
        }

        def dispositionSql = ""
        if (riskWarningStatus || riskWarningDispositionType)
        {
            def dispositionList = ContactRiskWarningDisposition.executeQuery(riskSql)*.contact.unique()
            if (dispositionList)
            {
                String dispositionIdList = dispositionList*.id?.toString()
                dispositionSql += " and e.id in (" + dispositionIdList?.substring(1, dispositionIdList.lastIndexOf("]")) + ")"
            }
            else
            {
                dispositionSql += " and e.id in ('-1')"
            }
        }

        def contactSql = " from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        def sql = " "
        if (dispositionSql)
        {
            sql += dispositionSql
        }
        // def highList = CreditScoreRiskDimension.findByLabel("高风险")
        def highList = CreditScoreRiskDimension.findByOrderNumber("1")
        def maxValue = highList?.maxValue
        sql += " and e.creditScore <= :maxValue "
        estateQueryParam['maxValue'] = new Double(maxValue)

        if (address && address != "")
        {
            sql += " and e.address like :address"
            estateQueryParam['address'] = '%' + address + '%'
        }
        if (debitCardNumber && debitCardNumber != "")
        {
            sql += " and e.debitCardNumber like :debitCardNumber"
            estateQueryParam['debitCardNumber'] = '%' + debitCardNumber + '%'
        }
        if (creditRiskLevel && creditRiskLevel != "")
        {
            def riskList = CreditScoreRiskDimension.list()
            riskList.each {
                if (it?.label == creditRiskLevel)
                {
                    def minScoreValue = it.minValue
                    def maxScoreValue = it.maxValue
                    sql += " and e.creditScore > :minScoreValue and e.creditScore <= :maxScoreValue "
                    estateQueryParam['minScoreValue'] = new Double(minScoreValue)
                    estateQueryParam['maxScoreValue'] = new Double(maxScoreValue)
                }
            }
        }
        if (cellphone && cellphone != "")
        {
            sql += " and e.cellphone like :cellphone"
            estateQueryParam['cellphone'] = '%' + cellphone + '%'
        }
        if (creditScoreStart && creditScoreStart != '')
        {
            sql += " and e.creditScore >= :creditScoreStart "
            estateQueryParam['creditScoreStart'] = new Double(creditScoreStart)
        }
        if (creditScoreEnd && creditScoreEnd != '')
        {
            sql += " and e.creditScore <= :creditScoreEnd "
            estateQueryParam['creditScoreEnd'] = new Double(creditScoreEnd)
        }
        if (fullName && fullName != "")
        {
            sql += " and e.fullName like :fullName"
            estateQueryParam['fullName'] = '%' + fullName + '%'
        }
        if (idNumber && idNumber != "")
        {
            sql += " and e.idNumber = :idNumber "
            estateQueryParam['idNumber'] = idNumber
        }
        if (identityType && identityType != "")
        {
            sql += " and e.identityType.id = :identityType "
            estateQueryParam['identityType'] = Long.parseLong(identityType)
        }
        if (batch && batch != "")
        {
            sql += " and e.batch.id = :batch "
            estateQueryParam['batch'] = Long.parseLong(batch)
        }

        def countSql = " select count(e.id) from Contact e where e.account.id in " + Account.FilterAccountSql(user)
        countSql += sql

        if (order && sort)
        {
            sql += " order by e.${sort} ${order}"
        }
        else
        {
            sql += " order by e.modifiedDate desc "
        }
        contactSql += sql
        def contactList = Contact.executeQuery(contactSql, estateQueryParam, [max: max, offset: offset])
        def contactCount = Contact.executeQuery(countSql, estateQueryParam)
        respond contactList, model: [contactList: contactList, contactCount: contactCount[0], params: params], view: 'contactRiskWarning'
    }

    def contactRiskWarningShow(Contact contact)
    {
        def mortgageList = MortgageContact.findAllByContact(contact)*.mortgage?.unique()
        respond contact, model: [mortgageList: mortgageList, contactDetail: contact], view: 'contactRiskWarningShow'
    }

    @Transactional
    def contactRiskWarningDisposal(ContactRiskWarningDisposition contactRiskWarningDisposition){
        def contactIds = params["contactIds"]
        def targetUri = request.getHeader("referer")
        if(contactIds){
            def idList = contactIds.split(",")
            println "===========idList="+idList
            idList?.each {
                Contact contact = Contact.findById(Long.parseLong(it))
                ContactRiskWarningDisposition newContactRiskWarningDisposition = new ContactRiskWarningDisposition()
                newContactRiskWarningDisposition.type = contactRiskWarningDisposition.type
                newContactRiskWarningDisposition.description = contactRiskWarningDisposition.description
                newContactRiskWarningDisposition.status = contactRiskWarningDisposition.status
                newContactRiskWarningDisposition.endDate = contactRiskWarningDisposition.endDate
                newContactRiskWarningDisposition.startDate = contactRiskWarningDisposition.startDate
                newContactRiskWarningDisposition.createBy = contactRiskWarningDisposition.createBy
                newContactRiskWarningDisposition.createdDate = contactRiskWarningDisposition.createdDate
                newContactRiskWarningDisposition.contact = contact
                if (newContactRiskWarningDisposition.validate())
                {
                    newContactRiskWarningDisposition?.save()
                }
                else
                {
                    println newContactRiskWarningDisposition?.errors
                }
            }
        }
        redirect url: targetUri
    }

    // 押品有效到期监测
    def effectiveMaturityWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def externalId = params['externalId']
        def name = params['name']
        def type = params['type']
        def expires = params['expires']
        def status = params['status']
        def communityId = params['communityId']
        def sql = "from RiskWarning r where r.type.code = '14' and r.isWarning = '1' "
        if (externalId)
        {
            sql += " and r.collateral.externalId like '%${externalId}%' "
        }
        if (name)
        {
            sql += " and r.collateral.name like '%${name}%' "
        }
        if (type) 
        {
            sql += " and r.collateral.type.id = ${type}"    
        }
        if (status) 
        {
            sql += " and r.status.id = '${status}' "
        }
        if (expires) 
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
            def currentDateStr = sdf.format(new Date())
            if (expires == "true") 
            {
                sql += " and r.collateral.estate.endDate < '${currentDateStr}'"
            }
            if (expires == "false") 
            {
                sql += " and r.collateral.estate.endDate >= '${currentDateStr}'"
            }
        }
        if(communityId){
            sql += " and r.collateral.estate.communityId = ${communityId} "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "
        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    押品有效到期监测详情页
    def effectiveMaturityWarningShow(Collateral collateral)
    {
        def estate = null
        if(!collateral){
            estate = Estate.findById(Long.parseLong(params["id"]))
            collateral = Collateral.findByEstate(estate)
            params.status = RiskWarning.findByCollateral(collateral)?.status?.name
        }else{
            estate = collateral?.estate
        }
        println "params:   "+params

        def zoneNumber = estate?.city?.zoneNumber
        def communityId = estate.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage

        def replaceCollateral = collateral?.replacementCollateral

        respond collateral, model: [params: params, mortgageList: mortgageList, estateDetail: estate, community: community['data'], replaceCollateral: replaceCollateral, communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']]
    }

    /**
     * 集中度风险
     */
    def concentrationWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '7' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    集中度预警押品详情页
    def concentrationWarningShow(Community community)
    {
        if(!community){
            def communityId = Long.parseLong(params['id'])
            community = Community.findByCommunityId(communityId)
        }
        respond community
    }

    //押品覆盖率预警
    def collateralCoverageRateWarning(Integer max)
    {
        params.max = Math.min(max ?: 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0
        def address = params['address']
        def communityName = params['communityName']
        def status = params['status']
        def sql = "from RiskWarning r where r.type.code = '10' and r.isWarning = '1' "
        if (address)
        {
            sql += " and r.community.address like '%${address}%' "
        }
        if (communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%' "
        }
        if (status)
        {
            sql += " and r.status.id = '${status}' "
        }
        def sql1 = " select count(*) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: params.max, offset: params.offset]).asList()
        def riskWarningCount = RiskWarning.executeQuery(sql1)
        respond riskWarningList, model: [riskWarningList: riskWarningList, riskWarningCount: riskWarningCount[0]]
    }

    //    押品覆盖率预警详情页
    def collateralCoverageRateWarningShow(Community community)
    {
        if(!community){
            def communityId = Long.parseLong(params['id'])
            community = Community.findByCommunityId(communityId)
        }
        respond community
    }

    //手机号停用预警
    def cellphoneStopWarning(){

    }

    //手机号停用预警详情
    def cellphoneStopWarningShow(){

    }

    //工作地点频繁预警
    def frequentlyWorkplaceWarning(){

    }

    //工作地点频繁预警详情
    def frequentlyWorkplaceWarningShow(){

    }

    // 押品效期预警（组件内容）
    // def effectiveMaturityInit()
    // {
    //     println "======================== effectiveMaturityInit  ============================"
    //     def count = 0
    //     def user = User.findById(springSecurityService.principal.id)
    //     def sql = "select new map(c.id as id, e.endDate as endDate) from Collateral c left join c.estate e where date_part('day', e.endDate - CURRENT_DATE) <= 1 and date_part('day', e.endDate - CURRENT_DATE) >= 0 and c.account.id in " + Account.FilterAccountSql(user)
    //     def result = Collateral.executeQuery(sql).asList()
    //     result?.each
    //     {
    //         def collateral = Collateral.findById(it?.id)
    //         def type = RiskWarningTypeDict.findByCode("14")
    //         def status = RiskWarningStatusDict.findByCode("2")
    //         def riskWarning = RiskWarning.findByCollateralAndType(collateral, type)
    //         if (!riskWarning)
    //         {
    //             riskWarning = new RiskWarning()
    //         }

    //         riskWarning.type = type
    //         riskWarning.collateral = collateral
    //         riskWarning.status = status
    //         if (riskWarning.validate())
    //         {
    //             riskWarning.save flush: true
    //             count++
    //         }
    //         else
    //         {
    //             println riskWarning.errors
    //         }
    //         println "warning counts: " + count
    //     }
    //     println "finish: " + count
    //     redirect action: 'effectiveMaturityWarning'
    // }

    // 小区评分预警（组件内容）
    // def buildingScoreInit()
    // {
    //     println "======================== buildingScoreInit  ============================"
    //     def count = 0
    //     def result = Community.findAllByCommunityScoreLessThan(3)
    //     result?.each
    //     {
    //         def type = RiskWarningTypeDict.findByCode("15")
    //         def status = RiskWarningStatusDict.findByCode("2")
    //         def riskWarning = RiskWarning.findByCommunityAndType(it, type)
    //         if (!riskWarning)
    //         {
    //             riskWarning = new RiskWarning()
    //         }

    //         riskWarning.type = type
    //         riskWarning.community = it
    //         riskWarning.status = status
    //         if (riskWarning.validate())
    //         {
    //             riskWarning.save flush: true
    //             count++
    //         }
    //         else
    //         {
    //             println riskWarning.errors
    //         }
    //         println "warning counts: " + count
    //     }

    //     println "finish: " + count

    //     redirect action: 'buildingScoreWarning'
    // }

//    押品覆盖率（组件内容）
    // def collateralCoverageRateInit()
    // {
    //     println "======================== collateralCoverageRateInit  ============================"

    //     def warningCounts = 0
    //     def communityCounts = 0
    //     def user = User.findById(springSecurityService.principal.id)
    //     def db = new groovy.sql.Sql(dataSource)
    //     def sql = "select community_id as id, count(*) as estatecounts, (select community.total_house_hold_count from community where community.community_id = estate.community_id) as housecounts from estate where community_id is not null and account_id in " + Account.FilterAccountSql(user) + " GROUP BY community_id"
    //     def result = db.rows(sql).asList()
    //     result?.each
    //     {
    //         def community = Community.findByCommunityId(it?.id)
    //         def estateCounts = it?.estatecounts
    //         def housecounts = it?.housecounts
    //         def communityCoverage = 0
    //         try
    //         {
    //             if (estateCounts && estateCounts != 0 && housecounts && housecounts != 0)
    //             {
    //                 communityCoverage = estateCounts / housecounts
    //             }

    //             if (!community?.communityCoverage)
    //             {
    //                 community?.communityCoverage = communityCoverage
    //                 community.save(flush: true)
    //                 communityCounts++
    //                 println communityCounts
    //                 if (communityCoverage >= 0.1)
    //                 {
    //                     def type = RiskWarningTypeDict.findByCode("10")
    //                     def status = RiskWarningStatusDict.findByCode("2")
    //                     def riskWarning = RiskWarning.findByCommunityAndType(community, type)
    //                     if (!riskWarning)
    //                     {
    //                         riskWarning = new RiskWarning()
    //                     }

    //                     riskWarning.type = type
    //                     riskWarning.community = community
    //                     riskWarning.status = status
    //                     riskWarning.save(flush: true)
    //                     warningCounts++
    //                     println "warningCounts:" + warningCounts
    //                 }
    //             }
    //         }
    //         catch(Exception e)
    //         {
    //             println e.printStackTrace()
    //         }
    //         db.commit()
    //     }

    //     println "finish: " + communityCounts
    //     println "finish: " + warningCounts

    //     redirect action: 'collateralCoverageRateWarning'
    // }

    /**
     * 预警处置
     */
    def riskWarningDeal()
    {
        def status = ""
        def riskWarningId = params['id']
        def riskWarning = RiskWarning.findById(riskWarningId)
        try
        {
            riskWarning.status = RiskWarningStatusDict.findByCode('3')
            riskWarning.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    /**
     * 预警删除
     */
    def riskWarningDelete()
    {
        def status = ""
        def riskWarningId = params['id']
        def riskWarning = RiskWarning.findById(riskWarningId)
        try
        {
            riskWarning.isWarning = false
            riskWarning.save flush: true
            status = "success"
        }
        catch (Exception e)
        {
            status = "false"
            e.printStackTrace()
        }
        render([status: status] as JSON)
    }

    // 组建执行
    def excuteComponent()
    {
        def componentCode = params['componentCode']
        def component = Component.findByCode(componentCode)
        def view = componentService.evaluate component
        redirect action: view
    }

    // 带service参数组件执行
    def excuteComponentWithParam()
    {
        def serviceParams = [springSecurityService: springSecurityService, apiService: apiService, dataSource: dataSource, scoreApiService: scoreApiService, riskWarningService: riskWarningService]
        def componentCode = params['componentCode']
        def component = Component.findByCode(componentCode)

        def view = componentService.evaluate(component, serviceParams)
        redirect action: view
    }

    //贷款预警列表
    def mortgageWarning(){

    }
    //贷款预警详情
    def mortgageWarningShow(Mortgage mortgage){
        mortgage = Mortgage.findById(515717)

        respond mortgage
    }

    // 预警处置页面
    def contactOverdueWarningEdit(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [mortgage: riskWarning?.mortgage, params: params]
    }

    def contactOverdueWarningEdit1(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [mortgage: riskWarning?.mortgage, params: params]
    }

    // 预警处置页面
    def workflowEdit(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [params: params]
    }

    // def mortgageWarningDisposalSave(RiskWarning riskWarning)
    // {
    //     if (riskWarning.validate()) 
    //     {
    //         riskWarning.save flush: true
    //     }
    //     else
    //     {
    //         println riskWarning.errors
    //     }
    //     def serviceParams = [springSecurityService: springSecurityService, riskWarning: riskWarning, riskWarningService: riskWarningService]
    //     def component = Component.findByCode("initRiskWarningDisposalFlow")

    //     componentService.evaluate(component, serviceParams)

    //     def user = User.findById(springSecurityService.principal.id)
    //     def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
    //     def roleSql = ""
    //     def roleList = UserRole.findAllByUser(user)*.role
    //     if (roleList) 
    //     {
    //         String roleIdList = roleList*.id?.toString()
    //         roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
    //     }

    //     def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
    //     if(!approveRoleFlag)
    //     {
    //         flash.message = "权限校验失败"
    //         redirect action:'contactOverdueWarning'
    //         return
    //     }

    //     def comment = new Comment()
    //     comment.riskWarning = riskWarning
    //     comment.warningStage = riskWarning?.stage
    //     comment.comment = params['comment']
    //     comment.save()

    //     def map = riskWarningService.approve(riskWarning)
    //     if(!map['flag'])
    //     {
    //         flash.message = map['message']
    //         redirect action:'contactOverdueWarning'
    //         return
    //     }

    //     redirect action: 'contactOverdueWarning'
    // }

    def mortgageWarningDisposalSave1()
    {
        def riskWarning = RiskWarning.findById(params['riskWarning'])
        def department = Department.findById(params['department'])
        riskWarning.disposalDepartment = department
        if (riskWarning.validate()) 
        {
            riskWarning.save flush: true
        }
        else
        {
            println riskWarning.errors
        }

        // def user = User.findById(springSecurityService.principal.id)
        // def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        // def roleSql = ""
        // def roleList = UserRole.findAllByUser(user)*.role
        // if (roleList) 
        // {
        //     String roleIdList = roleList*.id?.toString()
        //     roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        // }

        // def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        // if(!approveRoleFlag)
        // {
        //     flash.message = "权限校验失败"
        //     redirect action:'overdueCollectionIndex'
        //     return
        // }

        // def map = riskWarningService.approve(riskWarning)
        // if(!map['flag'])
        // {
        //     flash.message = map['message']
        //     redirect action:'overdueCollectionIndex'
        //     return
        // }

        redirect url: request.getHeader('referer')
    }

    def mortgageWarningDisposalAsign(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader("referer")
        respond riskWarning, model: [mortgage: riskWarning?.mortgage, params: params]
    }

    def mortgageWarningDisposalAsignSave(RiskWarning riskWarning)
    {
        if (riskWarning.validate()) 
        {
            riskWarning.save flush: true
        }
        else
        {
            println riskWarning.errors
        }

        redirect url: params['targetUri']
    }

    // 登记流程推进
    def approve(RiskWarning riskWarning)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList) 
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if(!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect url: request.getHeader("referer")
            return
        }

        // 校验是否提交备注
        def comment = Comment.findByRiskWarningAndWarningStage(riskWarning, riskWarning?.stage)
        if(!comment)
        {
            flash.message = "未提交审批意见"
            redirect url: request.getHeader("referer")
            return
        }

        def map = riskWarningService.approve(riskWarning)
        if(!map['flag'])
        {
            flash.message = map['message']
            redirect url: request.getHeader("referer")
            return
        }

        redirect action: 'contactOverdueWarningIndex'
    }

    def reject(RiskWarning riskWarning)
    {
        def user = User.findById(springSecurityService.principal.id)
        def flowStage = RiskWarningFlowStage.findByRiskWarningAndStage(riskWarning, riskWarning?.stage)
        def roleSql = ""
        def roleList = UserRole.findAllByUser(user)*.role
        if (roleList) 
        {
            String roleIdList = roleList*.id?.toString()
            roleSql += " and role.id in (" + roleIdList?.substring(1, roleIdList.lastIndexOf("]")) + ")"
        }

        def approveRoleFlag = RiskWarningFlowStageRole.find("from RiskWarningFlowStageRole where flowStage.id = ? and teamRole.id = ? " + roleSql, [flowStage?.id, TeamRole.APPROVAL()?.id]) && true
        if(!approveRoleFlag)
        {
            flash.message = "权限校验失败"
            redirect url: request.getHeader("referer")
            return
        }

        def canReject = riskWarningService.reject(riskWarning)
        if (canReject)
        {
            def comment = new Comment()
            comment.riskWarning = riskWarning
            comment.warningStage = riskWarning?.stage
            comment.comment = params['comment']
            comment.save()

            redirect action: params['targetUri']
        }
        else
        {
            flash.message = "对不起，无权限拒绝"
            redirect url: request.getHeader("referer")
            return
        }
    }

    def initWarningFlow(RiskWarning riskWarning)
    {
        def workFlow = riskWarning?.workflow
        if (!workFlow) 
        {
            flash.message = "请先选择工作流"
            redirect url: request.getHeader("referer")
            return
        }
        riskWarningService.initRiskWarningFlow(riskWarning, workFlow) 

        redirect url: request.getHeader("referer")
    }

    def riskWarningAnalyze()
    {

    }

    def riskWarningCollateral()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def warningType = params["warningType"]?.toLong()
        def serialNumber = params["serialNumber"]
        def externalId = params["externalId"]
        def address = params["address"]

        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.collateral.id is not null and r.bankAccount.id = ${user?.account?.id}"
        if(serialNumber)
        {
            sql += " and r.serialNumber like '%${serialNumber}%' "
        }
        if (externalId)
        {
            sql += " and r.collateral.externalId like '%${externalId}%'"
        }
        if (address)
        {
            sql += " and r.collateral.estate.sourceAddress like '%${address}%'"
        }
        if (warningType) 
        {
            sql += " and r.type.id = ${warningType}"
        }
        def countSql = "select count(r.id) " + sql
        sql += " order by r.modifiedDate desc "
        
        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)

        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0]]
    }

    def riskWarningCollateralShow(RiskWarning riskWarning)
    {
        def collateral = riskWarning?.collateral
        def estate = collateral?.estate
        def zoneNumber = estate?.city?.zoneNumber
        def communityId = estate?.communityId
        //小区详情
        def community = apiService.community(zoneNumber, communityId)
        //小区照片
        def communityPicArr = apiService.picture(zoneNumber, communityId, 5, 3)
        //成交案例列表
        def saleList = apiService.sale(zoneNumber, communityId)
        //挂牌案例列表
        def listings = apiService.listing(zoneNumber, communityId)
        // 贷款信息
        def mortgageList = MortgageCollateral.findAllByCollateral(collateral)*.mortgage

        def replaceCollateral = collateral?.replacementCollateral

        def layout = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName('Pending'))?.stage?.layout?.name

        respond riskWarning, model: [collateral: collateral, mortgageList: mortgageList, estateDetail: estate, community: community['data'], replaceCollateral: replaceCollateral, communityPicArr: communityPicArr['data'], saleList: saleList['data'], listings: listings['data']], view: layout
    }

    def riskWarningMortgage()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def warningType = params["warningType"]?.toLong()
        def serialNumber = params["serialNumber"]
        def mortgageSerialNumber = params["mortgageSerialNumber"]
        def defaultStart = params['defaultStart']
        def defaultEnd = params['defaultEnd']
        def overdueStart = params['overdueStart']
        def overdueEnd = params['overdueEnd']

        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.mortgage.id is not null and r.bankAccount.id = ${user?.account?.id}"
        if(serialNumber)
        {
            sql += " and r.serialNumber like '%${serialNumber}%' "
        }
        if (mortgageSerialNumber)
        {
            sql += " and r.mortgage.serialNumber like '%${mortgageSerialNumber}%'"
        }
        if (defaultStart && defaultStart != "")
        {
            sql += " and r.mortgage.curDefaultingDuration >= ${defaultStart}"
        }
        if (defaultEnd && defaultEnd != "")
        {
            sql += " and r.mortgage.curDefaultingDuration <= ${defaultEnd}"
        }
        if (overdueStart && overdueStart != "")
        {
            sql += " and r.mortgage.curOverdueDuration >= ${overdueStart}"
        }
        if (overdueEnd && overdueEnd != "")
        {
            sql += " and r.mortgage.curOverdueDuration <= ${overdueEnd}"
        }
        if (warningType) 
        {
            sql += " and r.type.id = ${warningType}"
        }
        def countSql = "select count(r.id) " + sql
        sql += " order by r.modifiedDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)

        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0]]
    }

    def riskWarningMortgageShow(RiskWarning riskWarning)
    {
        def mortgage = riskWarning?.mortgage
        def layout = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName('Pending'))?.stage?.layout?.name
        respond mortgage, model: [params: params, riskWarning: riskWarning, contact: mortgage.mortgageContact], view: layout
    }

    def riskWarningCommunity()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def serialNumber = params["serialNumber"]
        def communityName = params["communityName"]
        def address = params["address"]
        def warningType = params["warningType"]?.toLong()
        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.community.id is not null and r.bankAccount.id = ${user?.account?.id}"
        if(serialNumber)
        {
            sql += " and r.serialNumber like '%${serialNumber}%' "
        }
        if(communityName)
        {
            sql += " and r.community.communityName like '%${communityName}%'"
        }
        if(address)
        {
            sql += " and r.community.address like '%${address}%'"
        }
        if (warningType) 
        {
            sql += " and r.type.id = ${warningType}"
        }
        def countSql = "select count(r.id) " + sql
        sql += " order by r.modifiedDate desc "
        
        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)
        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0]]
    }

    def riskWarningCommunityShow(RiskWarning riskWarning)
    {
        def community = riskWarning?.community
        def list = communityService.getCommunityScore(community?.city?.zoneNumber, community?.communityId)
        def layout = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName('Pending'))?.stage?.layout?.name
        respond list, model: [riskWarning: riskWarning, community: community], view: layout
    }

    def riskWarningContact()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def serialNumber = params["serialNumber"]
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]
        def idNumber = params["idNumber"]
        def warningType = params["warningType"]?.toLong()
        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.contact.id is not null and r.bankAccount.id = ${user?.account?.id}"
        if(serialNumber)
        {
            sql += " and r.serialNumber like '%${serialNumber}%' "
        }
        if(fullName)
        {
            sql += " and r.contact.fullName like '%${fullName}%' "
        }
        if(cellphone)
        {
            sql += " and r.contact.cellphone like '%${cellphone}%' "
        }
        if(idNumber)
        {
            sql += " and r.contact.idNumber like '%${idNumber}%' "
        }
        if (warningType) 
        {
            sql += " and r.type.id = ${warningType}"
        }
        def countSql = "select count(r.id) " + sql
        sql += " order by r.modifiedDate desc "
        
        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)
        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0]]
    }

    def riskWarningContactShow(RiskWarning riskWarning)
    {
        def contact = riskWarning?.contact
        def result = developerApiService.getContactInfo("513001197308010223","叶紫云")
        def gongkai = contactService.getByType(1, result)
        def laolai = contactService.getByType(2, result)
        def xiangao = contactService.getByType(3, result)
        def xianchu = contactService.getByType(4, result)
        def caipan = contactService.getByType(5, result)
        def shenpan = contactService.getByType(6, result)
        def zuifan = contactService.getByType(7, result)

        def layout = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName('Pending'))?.stage?.layout?.name

        //贷款信息
        def mortgageList = MortgageContact.findAllByContact(contact)*.mortgage?.unique()
        respond riskWarning, model: [mortgageList: mortgageList, contactDetail: contact,gongkai: gongkai,laolai:laolai,xiangao:xiangao,xianchu:xianchu,caipan:caipan,shenpan:shenpan,zuifan:zuifan], view: layout
    }

    def riskWarningAccount()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def city = params["city"]
        def warningType = params["warningType"]?.toLong()
        def district = params["district"]
        def operatingState = params["operatingState"]
        def fullName = params["fullName"]
        def workflowStatus = params["workflowStatus"]
        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.account.id is not null and r.bankAccount.id = ${user?.account?.id}"
        if(name)
        {
            sql += " and r.account.name like '%${name}%' "
        }
        if(city && city != '-1')
        {
            sql += " and r.account.city.zoneNumber = '${city}'"
        }
        if(district && district != '-1')
        {
            sql += " and r.account.district.zoneNumber = '${district}'"
        }
        if(operatingState)
        {
            sql += " and r.account.operatingState = '${operatingState}'"
        }
        if(fullName)
        {
            sql += " and r.account.fullName like '%${fullName}%' "
        }
        if(workflowStatus)
        {
            sql += " and r.workflowStatus = '${workflowStatus}'"
        }
        if (warningType) 
        {
            sql += " and r.type.id = ${warningType}"
        }
        def countSql = "select count(r.id) " + sql
        sql += " order by r.modifiedDate desc "
        
        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0], districtList: districtList]
    }

    def riskWarningAccountShow(RiskWarning riskWarning)
    {
        def account = riskWarning?.account
        def user = User.findById(springSecurityService.principal.id)

        //开发商负面信息
        def companyInfo = developerApiService.getOrginInfo(account?.name)
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }

        def inf = new HashMap<String,String>()
        inf.put("companyName",account?.name)

        //处理负面信息
        List<Map<String,String>> list = new ArrayList<HashMap<String,String>>()

        //执行金额
        def zhixingMoney = 0
        //欠税金额
        def qianshuiMoney = 0
        //失信被执行金额
        def shixinMoney = 0
        //欠款欠税金额
        def qiankuanMoney = 0
        //被裁判金额
        def caipanMoney = 0

        //民事审批被告记录
        def shenpanCount = 0
        //那种是否正常
        boolean  isNormal = true
        //被限制出境人数
        def xianchuCount  = 0
        //被限制高消费人数
        def xiangaoCount = 0
        //行政违法记录
        def weifaCount = 0
        //犯罪嫌疑人
        def fanzuiCount = 0


        //执行公开信息
        companyInfo?.企业单笔精确?.fxcontent?.zhixing?.each{
            zhixingMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","执行公开信息")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //失信被执行信息
        companyInfo?.企业单笔精确?.fxcontent?.shixin?.each{
            shixinMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","失信被执行信息")
            map.put("name",it?.name)
            map.put("money",it?.wlmoney)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制高消费记录
        companyInfo?.企业单笔精确?.fxcontent?.xiangao?.each{
            xiangaoCount++
            Map map = new HashMap()
            map.put("type","限制高消费记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制出入境记录
        companyInfo?.企业单笔精确?.fxcontent?.xianchu?.each{
            xianchuCount++
            Map map = new HashMap()
            map.put("type","限制出入境记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事裁判记录
        companyInfo?.企业单笔精确?.fxcontent?.caipan?.each{
            caipanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","民事裁判记录")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事审判记录
        companyInfo?.企业单笔精确?.fxcontent?.shenpan?.each{
            shenpanCount++
            Map map = new HashMap()
            map.put("type","民事审判记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //罪犯及嫌疑人记录
        companyInfo?.企业单笔精确?.fxcontent?.zuifan?.each{
            fanzuiCount++
            Map map = new HashMap()
            map.put("type","罪犯及嫌疑人记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //行政违法记录
        companyInfo?.企业单笔精确?.fxcontent?.weifa?.each{
            weifaCount++
            Map map = new HashMap()
            map.put("type","行政违法记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠税名单
        companyInfo?.企业单笔精确?.fxcontent?.qianshui?.each{
            qianshuiMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠税名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.taxperiod)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //纳税非正常户
        companyInfo?.企业单笔精确?.fxcontent?.feizheng?.each{
            isNormal = false
            Map map = new HashMap()
            map.put("type","纳税非正常户")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠款欠费名单
        companyInfo?.企业单笔精确?.fxcontent?.qiankuan?.each{
            qiankuanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠款欠费名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        list.each {
            it?.content = it.content.replace("<p>","").replace("</p>","")
        }

        def layout = WorkflowInstance.findByRiskWarningAndStatus(riskWarning, WorkflowInstanceStatus.findByName('Pending'))?.stage?.layout?.name

        respond riskWarning, model: [params: params,zhixingMoney:(zhixingMoney/10000).toInteger(),
                                 qianshuiMoney:(qianshuiMoney/10000).toInteger(),shixinMoney:(shixinMoney/10000).toInteger(),qiankuanMoney:(qiankuanMoney/10000).toInteger(),
                                 caipanMoney:(caipanMoney/10000).toInteger(),shenpanCount:shenpanCount,isNormal:isNormal,xianchuCount:xianchuCount,xiangaoCount:xiangaoCount,
                                 weifaCount:weifaCount,fanzuiCount:fanzuiCount,fumianList:list, account: account], view: layout
    }

    // 机构预警处置页面
    def riskWarningAccountEdit(RiskWarning riskWarning)
    {
        params['targetUri'] = request.getHeader('referer')
        respond riskWarning, model: [params: params]
    }

    def riskWarningDeveloperIndex(){

    }
    //开发商预警
    def riskWarningAccountDeveloper()
    {
        def max = params.max ? params.max.toInteger() : 10
        def offset = params.offset ? params.offset.toInteger() : 0
        def name = params["name"]
        def city = params["city"]
        def district = params["district"]
        def code = params["code"]
        def user = User.findById(springSecurityService.principal.id)
        def sql = " from RiskWarning r where r.account.type.code = 'DeveloperAccount' and r.bankAccount.id = ${user?.account?.id}"
        def querySql = " "
        if(name)
        {
            querySql += " and r.account.name like '%${name}%' "
        }
        if(city && city != '-1')
        {
            querySql += " and r.account.city.zoneNumber = '${city}'"
        }
        if(district && district != '-1')
        {
            querySql += " and r.account.district.zoneNumber = '${district}'"
        }

        def countSql = "select count(r.id) " + sql
        sql += querySql + " order by r.createdDate desc "

        def riskWarningList = RiskWarning.executeQuery(sql, [max: max, offset: offset])
        def riskWarningCount = RiskWarning.executeQuery(countSql)
        def districtList = District.findAllByParentAreaAndAreaLevel(City.findByZoneNumberAndAreaLevel(city, 2), 3)
        respond riskWarningList, model: [riskWarningCount: riskWarningCount[0], districtList: districtList]
    }
    def riskWarningDeveloperShow(RiskWarning riskWarning){
        respond Account.list()[0]
    }

    //法人、股东预警riskWarningAccountProject
    def riskWarningLegalRepresentative(){

    }

    //项目风险预警
    def riskWarningAccountProject(){

    }

    //销售统计预警
    def riskWarningAccountSales(){

    }

    //舆情预警
    def riskWarningAccountPublicOpinion(){

    }
}
